package com.example.hello.mapper;

import com.example.hello.pojo.Interaction;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface InteractionMapper {

    /**
     * 查找所有的交互记录
     * @return
     */
    @Select("SELECT id, user_id as userId, book_id as bookId, rating, is_favorite as isFavorite, borrow_count as borrowCount FROM user_book_interaction")
    List<Interaction> getAllInteractions();

    // 新增方法：根据 userId 和 bookId 查询评分
    @Select("SELECT rating FROM user_book_interaction WHERE user_id = #{userId} AND book_id = #{bookId} LIMIT 1")
    Double getRatingByUserAndBook(@Param("userId") Integer userId, @Param("bookId") Integer bookId);

    // 根据 userId 和 bookId 查询该条记录
    @Select("SELECT id, user_id as userId, book_id as bookId, rating, is_favorite as isFavorite, borrow_count as borrowCount " +
            "FROM user_book_interaction WHERE user_id = #{userId} AND book_id = #{bookId} LIMIT 1")
    Interaction findByUserAndBook(@Param("userId") Integer userId, @Param("bookId") Integer bookId);

    // 插入一条新的记录
    @Insert("INSERT INTO user_book_interaction (user_id, book_id, rating, is_favorite, borrow_count) " +
            "VALUES (#{userId}, #{bookId}, #{rating}, #{isFavorite}, #{borrowCount})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insertInteraction(Interaction interaction);

    // 更新 is_favorite 字段
    @Update("UPDATE user_book_interaction SET is_favorite = #{isFavorite} " +
            "WHERE user_id = #{userId} AND book_id = #{bookId}")
    void updateFavorite(@Param("userId") Integer userId, @Param("bookId") Integer bookId, @Param("isFavorite") boolean isFavorite);

    // 更新记录中的 rating 字段
    @Update("UPDATE user_book_interaction SET rating = #{rating} WHERE user_id = #{userId} AND book_id = #{bookId}")
    void updateRating(@Param("userId") Integer userId, @Param("bookId") Integer bookId, @Param("rating") double rating);

    // 更新记录中 borrow_count 加 1
    @Update("UPDATE user_book_interaction SET borrow_count = borrow_count + 1 " +
            "WHERE user_id = #{userId} AND book_id = #{bookId}")
    void updateBorrowCount(@Param("userId") Integer userId, @Param("bookId") Integer bookId);

    // 新增方法：根据 userId 查询该用户所有收藏记录（is_favorite 为 true）
    @Select("SELECT id, user_id as userId, book_id as bookId, rating, is_favorite as isFavorite, borrow_count as borrowCount " +
            "FROM user_book_interaction WHERE user_id = #{userId} AND is_favorite = true")
    List<Interaction> getFavoriteInteractionsByUser(@Param("userId") Integer userId);




}
